<template>
  <!-- 详情 -->
  <el-dialog
    v-el-drag-dialog
    title="安检计划"
    :visible.sync="visible"
    width="1024px"
    append-to-body
    @close="reset"
  >
    <div class="item">
      <div class="title">
        <span class="title-icon" />
        <span class="title-text">安检计划信息</span>
      </div>
      <el-descriptions size="medium">
        <el-descriptions-item label="编号">{{ temp.planCode }}</el-descriptions-item>
        <el-descriptions-item label="计划名称">{{ temp.planName }}</el-descriptions-item>
        <el-descriptions-item label="客户类型">{{ csmTypes }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions size="medium">
        <el-descriptions-item label="安检范围" label-class-name="checkscope" content-class-name="checkscopeContent">{{ temp.scopeNames }}</el-descriptions-item>
      </el-descriptions>
    </div>
    <div class="item">
      <el-form ref="dataForm" class="form" label-position="left" label-width="80px">
        <el-form-item label="备注:" style="width: 100%;">
          <el-input
            v-model="remark"
            type="textarea"
            resize="none"
            placeholder="请输入"
            maxlength="80"
            show-word-limit
          />
        </el-form-item>
      </el-form>
    </div>
    <div class="item">
      <div class="title">
        <span class="title-icon" />
        <span class="title-text">安检客户</span>
      </div>
      <div style="margin-bottom: 10px;">
        <el-button type="primary" @click="addClient">增加</el-button>
        <el-button type="primary" @click="del">删除</el-button>
      </div>
      <lb-table
        ref="lbTable"
        v-loading="$loadingPlugin.fetchData"
        v-el-height-adaptive-table="{bottomOffset:10}"
        border
        highlight-current-row
        element-loading-text="加载中"
        :column="column"
        :data="tableData.data"
        pagination
        :immediate-fetch="false"
        :total="tableData.total"
        custom-column
        @fetch="fetchData"
      />
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="reset">关闭</el-button>
      <el-button type="primary" size="mini" :loading="loading" @click="save">保 存</el-button>
    </div>
    <plan-add ref="planadd" :csm-type-map="csmTypeMap" :tree-data="treeData" :csm-status-map="csmStatusMap" @upDataNewlyIncreased="upDataNewlyIncreased" />
  </el-dialog>
</template>

<script>
  import {
    gasCheckPlanClientAssignDelete,
    gasCheckPlanClientAssignUpdate,
    gasCheckPlanClientScopename,
    gasCheckPlanClientListAdd
  } from '@/api'
  import { formatColumnMap } from '@/utils'
  import PlanAdd from './PlanAdd.vue'

  export default {
    name: 'newly-increased',
    components: {
      PlanAdd
    },
    props: {
      csmTypeMap: {
        type: Array,
        required: true
      },
      treeData: {
        type: Array,
        required: true
      },
      csmStatusMap: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        loading: false,
        visible: false,
        headerCheckbox: false,
        temp: {},
        remark: '',
        tableData: { // 安检人员明细
          total: 0,
          data: []
        }
      }
    },
    computed: {
      csmTypes() {
        var csmTypeStr = ''
        for (var i in this.csmTypeMap) {
          var item = this.csmTypeMap[i]
          if ((this.temp.csmTypes & (1 << item.value)) > 0) {
            csmTypeStr += item.desc + '\ '
          }
        }
        console.log(csmTypeStr)
        return csmTypeStr
      },
      column: function() {
        return [
          {
            prop: 'isCheckbox',
            align: 'center',
            width: 60,
            renderHeader: (h, { row }) => {
              return h('div', [
                h('el-checkbox', {
                  props: {
                    value: this.headerCheckbox
                  },
                  on: {
                    change: this.changeBox
                  }
                })
              ])
            },
            render: (h, { row, $index }) => {
              return h('el-checkbox', {
                props: {
                  value: row.isCheckbox
                },
                on: {
                  change: () => { this.onChangeBox($index) }
                }
              })
            }
          },
          {
            type: 'index'
          },
          {
            prop: 'csmCode',
            label: '客户编号'
          },
          {
            prop: 'csmName',
            label: '客户名称'
          },
          {
            prop: 'csmType',
            label: '客户类型',
            render: (h, { row }) => <span>{row.csmType && formatColumnMap(this.csmTypeMap, 'value', row.csmType, 'desc')}</span>
          },
          {
            prop: 'csmPhone',
            label: '客户电话'
          },
          {
            prop: 'orgName',
            label: '所属机构'
          },
          {
            prop: 'csmAddress',
            label: '地址'
          }
        ]
      }
    },
    created() {},
    methods: {
      async open(temp) {
        console.log('temp', temp)
        this.temp = temp
        this.remark = temp.remark ? temp.remark : ''
        await Promise.all([this.getScopeName()])
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          this.$nextTick(() => {
            this.$refs.lbTable.fetch({ currentPage: 1 })
          })
        })
      },
      // 获取安检范围
      async getScopeName() {
        const res = await gasCheckPlanClientScopename({
          planCode: this.temp.planCode
        })
        this.temp.scopeNames = res.data && res.data.scopeName
      },
      // 全选/反选
      changeBox(val) {
        this.headerCheckbox = val
        this.tableData.data = this.tableData.data.map(item => {
          return { ...item, isCheckbox: val }
        })
      },
      onChangeBox(ind) {
        this.tableData.data = this.tableData.data.map((item, index) => {
          if (ind === index) {
            item.isCheckbox = !item.isCheckbox
          }
          return { ...item }
        })
        const flag = this.tableData.data.every(item => item.isCheckbox === true)
        if (flag) {
          this.headerCheckbox = true
        } else {
          this.headerCheckbox = false
        }
      },
      // 增加
      addClient() {
        this.$refs.planadd.open(this.temp.planCode)
      },
      // 删除
      async del() {
        const flag = this.tableData.data.every(item => item.isCheckbox === false)
        if (flag) {
          this.$message({
            type: 'warning',
            message: '请至少选中一行'
          })
          return
        }
        var arr = []
        this.tableData.data.filter(item => {
          if (item.isCheckbox === true) {
            arr.push(item.csmAddressId)
          }
        })
        const { status } = await gasCheckPlanClientAssignDelete({
          planCode: this.temp.planCode,
          csmAddressIds: arr.join(',')
        })
        if (status === 200) {
          this.headerCheckbox = false
          this.$refs.lbTable.fetch({ currentPage: 1 })
        }
      },
      upDataNewlyIncreased() {
        console.log('更新')
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 保存
      async save() {
        this.loading = true
        await gasCheckPlanClientAssignUpdate({
          planCode: this.temp.planCode,
          remark: this.remark
        })
        setTimeout(() => {
          this.loading = false
        }, 1000)
        this.visible = false
        this.$emit('upDataTable')
      },
      // 安检客户
      async fetchData({ currentPage, pageSize }) {
        const params = {
          planCode: this.temp.planCode,
          pageIndex: currentPage,
          pageSize
        }
        const res = await gasCheckPlanClientListAdd(params)
        this.tableData.data = res.data.rows.map(item => {
          return { ...item, isCheckbox: false }
        })
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      reset() {
        this.visible = false
        this.temp = {}
        this.$emit('upDataTable')
      }
    }
  }
</script>

<style lang="scss" scoped>
/deep/ .el-table__empty-block {
  width: auto !important;
}
.item {
  // margin-bottom: 30px;
  .title {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    .title-icon {
      display: inline-block;
      width: 4px;
      height: 18px;
      margin-right: 6px;
      background: #01999f;
    }
    .title-text {
      font-family: Microsoft YaHei, Microsoft YaHei-Bold;
      font-size: 14px;
      font-weight: 700;
      color: #01999f;
    }
  }
  &:last-child {
    margin-bottom: 0;
  }
  .content {
    margin-bottom: 30px;
  }
  /deep/.checkscope {
    display: inline-block;
    width: 60px;
  }
  /deep/.checkscopeContent {
    flex: 1;
  }
}
</style>
